package util

import (
	"fmt"
	"github.com/llightos/efind"
	"log"
)

func GetGatawayLeader(etcdAddr string) string {
	client := efind.NewClient(efind.Config{
		EtcdAddr: etcdAddr,
		TTL:      2,
	})
	fmt.Println("获取零信任网关Leader节点")
	server, _ := client.MatchAServer("/etcd/gataway")
	return server.Val
}

func GetKeyCenterLeader(etcdAddr string) string {
	client := efind.NewClient(efind.Config{
		EtcdAddr: etcdAddr,
		TTL:      5,
	})
	fmt.Println("获取密钥生成中心Leader节点")
	server, _ := client.MatchAServer("/etcd/keycenter")
	return server.Val
}

// 要求以协程方式运行
func New(electName, electValue string) {
	//设置etcd节点名
	client := efind.NewClient(efind.Config{
		EtcdAddr: "192.168.146.1:2379",
		TTL:      5,
	})
	// 按照go.etcd.io/etcd/client/v3/concurrency包的安排，会先指定一个事件
	session, err := client.NewSession()
	if err != nil {
		log.Panicln(err)
		return
	}
	// 选举名和选举内容
	elect := session.NewElect(electName, electValue)
	go elect.LogReturnLeader()
	fmt.Println("elect.Info()", elect.Info())
	// 阻塞进行选举
	err = elect.Campaign()
	fmt.Println("我成Leader了")
	if err != nil {
		log.Panicln(err)
		return
	}
}
